// pages/map/index.js
import { getMap, getExhibit, getHot} from '../../http/interface.js'
const { formatAudio, timestr2sec } = require('../../utils/util.js');
const bgMusic = wx.getBackgroundAudioManager();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    banner: [],
    indicatorDots: false,
    vertical: false,
    autoplay: false,
    interval: 2000,
    duration: 500,
    currentIndex:0,
    showA:true,
    sdfwer: 1,
    hotS:[],
    ratio: 0,
    hot:false,
    site:false,//周边的site
    map_id:'',//当前地图id
    mapHeight: '', //地图图片高度
    exhibits:[],// 展品列表
    audio:"",//播放音频
    scale:"",//地图缩放比
    offset: 0, //进度条进度
    x:0,
    y:0,
    currentTime: '',
    maxTime: '', //总时长（字符串）
    max: '', //总时长（秒）
    playing: false, //正在播放
    over: false, //语音结束
  },
  playAudio(event){
    var index = event.currentTarget.dataset.index;
    wx.navigateTo({
      url: '/pages/exhition/exhibition?id='+this.data.exhibits[index].exhibit_id ,
    })
   
  },
  getMapList(){
    getMap(0).then(res=>{
      if(res.data.length>0){
        this.setData({
          banner: res.data
        })
        this.data.map_id = res.data[0].map_id;
        var scale = 750 / this.data.banner[this.data.currentIndex].width;
        console.log(scale);
        this.setData({
          x:40,
          y:120,
          radio:scale,
          sdfwer: 1, //地图缩放
          scale: 1/2,
          mapHeight: parseInt(this.data.banner[this.data.currentIndex].height * 750 / this.data.banner[this.data.currentIndex].width),
        })
        if(this.data.showA){
          this.getExhibits(this.data.map_id);
        }
      }
    })
  },
  //音频初始化
  audioInit() {
    var that = this;
    bgMusic.onPlay(() => {
      // console.log('详情页开播了');
      bgMusic.duration //类似初始化-必须触发-不触发此函数延时也获取不到！！！！！！！！！！！！！！！
      wx.setStorage({
        key: 'bjaudioId',
        data: that.data.audio.exhibit_id,
      })

      setTimeout(function () {
        that.setData({
          playing: true,
          // 获取时长
          maxTime: formatAudio(Math.round(bgMusic.duration)),
        })
      }, 100) //这里设置延时获取
    });

    bgMusic.onPause(() => {
      // console.log('详情页暂停了');
      that.setData({
        playing: false,
      });
    });

    bgMusic.onTimeUpdate(() => {
      const bjaudioId = wx.getStorageSync('bjaudioId');

      if (!bgMusic.paused) {
        console.log()
        if (bgMusic.src == that.data.audio.audio && bjaudioId == that.data.audio.exhibit_id) {
          that.setData({
            playing: true,
            offset: Math.round(bgMusic.currentTime),
            currentTime: formatAudio(Math.round(bgMusic.currentTime)),
            maxTime: formatAudio(Math.round(bgMusic.duration))
          });
        } else {
          bgMusic.stop()
        }
      }
    });

    bgMusic.onEnded(() => {
      // console.log('详情页播完了');

      that.setData({
        playing: false,
        offset: 0,
        over: true,
      });

      wx.removeStorage({
        key: 'bjaudioId',
        success(res) {
          console.log(res)
        }
      })
    });

    bgMusic.onStop(() => {
      // console.log('详情页关闭了');
      that.setData({
        playing: false,
        over: true,
      });
    });

  },

  play() { //播放讲解词
    var that = this;
    var bjaudioId = wx.getStorageSync('bjaudioId');
    
    if (that.data.playing) {
      bgMusic.pause();
    } else {
      if (bgMusic.src == that.data.audio && bjaudioId== that.data.audio.exhibit_id) {
    
        if (that.data.over) { //播放完成后需要再赋值一次才能再播放
          bgMusic.string = '滨海科技馆';
          bgMusic.src = that.data.audio.audio;
          bgMusic.title = that.data.audio.exhibit_name;
          bgMusic.coverImgUrl = that.data.exhibit_list; //封面图 URL，用于做原生音频播放器背景图。
        } else {
          bgMusic.play();
        }
      } else {
        // 首次播放
        if (that.data.audio.audio) {
          bgMusic.string = '滨海科技馆';
          bgMusic.src = that.data.audio.audio; //默认为空字符串，当设置了新的 src 时，会自动开始播放，目前支持的格式有 m4a, aac, mp3, wav。
          console.log(that.data.audio.audio)
          bgMusic.title = that.data.audio.exhibit_name;
          bgMusic.coverImgUrl = that.data.audio.exhibit_list;
          console.log(that.data.audio)
          wx.setStorage({
            key: 'bjaudioId',
            data: that.data.audio.exhibit_id,
          })
        } else {
          wx.showToast({
            title: '暂无资源',
            icon: 'none'
          });
        }
      }
    };
  },
  sliderChange(e) {
    var that = this;
    if (e.detail.value) {
      if (!that.data.playing) {
        bgMusic.string = '';
        bgMusic.src = that.data.audio.audio;
        bgMusic.title = that.data.audio.exhibit_name;
        bgMusic.coverImgUrl = that.data.audio.exhibit_list;
        wx.setStorage({
          key: 'bjaudioId',
          data: that.data.audio.exhibit_id,
        })
        setTimeout(function () {
          bgMusic.seek(e.detail.value);
        }, 100)
      } else {
        bgMusic.seek(e.detail.value);
      }
    }
  },
  // 获取展品数
  getExhibits(id) {
    getExhibit(id).then(res => {
      this.setData({
        exhibits:res.data
      })
    })
  },
  swiperChange: function (e) {
    var that = this;
    var scale = 750 / this.data.banner[this.data.currentIndex].width;
    that.setData({
      currentIndex: e.detail.current,
      map_id:this.data.banner[e.detail.current].map_id,
      y:120,
      x:40,
      radio:scale,
      sdfwer: 1, //地图缩放
      scale: 1/2,
      mapHeight: parseInt(that.data.banner[that.data.currentIndex].height * 750 / that.data.banner[that.data.currentIndex].width),
    })
    if(that.data.showA){
      that.getExhibits(that.data.banner[e.detail.current].map_id)
    }
    if(that.data.hot){
      that.getHots()
    }
  },
  //控制显示语音显示
  changeShowA(){
    this.setData({
      showA: !this.data.showA,
      hot: false,
    })
    if(this.data.showA){
      this.getExhibits(this.data.banner[this.data.currentIndex].map_id);
    }
    
  },
  /**
     * @地图缩放
     */
    movablescale(e) {
      var that = this;
      let aa = 1 / e.detail.scale;
      that.setData({
          scaleOld: aa
      })
  },
  /**
   * @触摸结束
   */
  touchend() {
      var that = this;
      console.log(that.data.scaleOld);
      that.setData({
          scale: that.data.scaleOld,
      });
  },
  //热点切换
  changeHot(){
    this.setData({
      showA: false,
      site:false,
      hot: !this.data.hot,
    })
    if(this.data.hot){
      this.getHots();
    }
    
  },
  // 获取热点
  getHots(){
     getHot().then(res=>{
      this.setData({
        hotS:res.data[this.data.currentIndex].hot
      })
     })
  },
  // 周边
  goSite(){
    this.setData({
      site:true,
      hot: false,
      showA: false
    })
    setTimeout(()=>{
      this.setData({
        site:false
      })
      wx.navigateTo({
        url: '/pages/site/index',
      })
    },500)
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getMapList()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})